import Koa from 'koa'
import log4js from 'koa-log4'
import config from '../config'

log4js.configure(config.log4Config)

const accessLog = log4js.getLogger('access')
const appLog = log4js.getLogger('application')

process.on('uncaughtException', (err) => {
  // 未捕获的异常处理
  appLog.error(err)
})

process.on('unhandledRejection', (reason, p) => {
  // 未捕获的promise异常处理
  appLog.error(reason, p)
})

export function regLog(app: Koa): void {
  app.use(log4js.koaLogger(accessLog, { level: 'auto' }))
  app.use(log4js.koaLogger(appLog, { level: 'auto' }))
  appLog.warn('application reboot!')
  // 捕获koa异常
  app.on('error', (err) => {
    appLog.error(err)
  })
}

export const logs = {
  appLog,
  accessLog
}
